<?php
include('configure.php');
include('class.db.php');
printHeader(false);
session_start();
//Archivio
include('class.archivio.writer.php');

$HOUR_FRACTION = array(0,30);
$DAY_OF_WEEK =   array("Lun","Mar","Mer","Gio","Ven","Sab","Dom");
$DAY_OF_WEEK_UK = array("Dom","Lun","Mar","Mer","Gio","Ven","Sab");
$DAY_OF_WEEK_LONG =   array("Lunedi'","Martedi'","Mercoledi'","Giovedi'","Venerdi'","Sabato","Domenica");
$DATA_TABLE = array();
$HOUR_IN_A_DAY = array();
$DATA_FILE ="cal.dat";
$NUMERI_TELEFONO=array();
$LISTA_ALLARMI=array();
$LISTA_RUBRICA_SMS=array();
$LISTA_RUBRICA_FAX=array();
$LISTA_RUBRICA_EMAIL=array();
$LISTA_ALR_ENABLE_SMS=array();
$LISTA_ALR_ENABLE_EMAIL=array();
$LISTA_ALR_ENABLE_FAX=array();
$TH_Table="";
$MYSQL_SEZIONI="";
$HeaderSez="";
$TITLE="";
$ADMIN='admin';
$USER='user';
$RISULTATI_PER_PAG=300;

function SaveData()
{
	global $DATA_FILE,$DATA_TABLE;
	file_put_contents($DATA_FILE,serialize($DATA_TABLE));
}

function LoadData()
{
	global $HOUR_FRACTION, $DAY_OF_WEEK, $DATA_TABLE,$HOUR_IN_A_DAY,$DATA_FILE;
	$HOUR_IN_A_DAY = array();
	for($h=0;$h<24;$h++)
	{
		foreach($HOUR_FRACTION as $i => $val)
		{
			$subkey=sprintf ("%02d:%02d:00" ,$h,$val);
			array_push($HOUR_IN_A_DAY,$subkey);
			foreach($DAY_OF_WEEK as $i => $day)
			{
				$key = $day . " " . $subkey;
				$DATA_TABLE[$key]= array();
			}
		}
	}
       
	$data = @file_get_contents($DATA_FILE);
	if($data)
	{
		$DATA_TABLE = unserialize($data);
	}
}

function incrementData($hour)
{
    list($h,$m)=explode(":", $hour);
    $m=(($m+30)%60);
    if( $m== 0)
        $h++;
    $result=sprintf ("%02d:%02d" ,$h,$m);
    return $result;
}

function PrintACell($day, $hour)
{
	global $DATA_TABLE;
        global $ADMIN;
        session_start();

        $array_local=array();
        $key = $day.  " " . $hour;
        $td='';
        $ukey=urlencode($key);
        if($ADMIN == $_SESSION['u_name'])
        {   
            $td='href="files/php/addnew.php?skey='.$ukey.'" rel="#overlay"';
            
        }
	if(count($DATA_TABLE[$key]) != 0)
	{
		print "\n<td $td class=\"date_has_event\">\n<div class=\"events\">\n<ul>\n";
		print "<li><span class=\"title\">$key => ".incrementData($hour)."</span></li>\n";
		foreach($DATA_TABLE[$key] as $phone)
		{
                                if(false == $array_local[$phone[1]])
                                    print "<li><span class=\"desc\">$phone[0] - $phone[1]</span></li>\n";
                                $array_local[$phone[1]]=$phone[0];
                                
		}
		print "</ul>\n</div>\n";
	}
	else
	{
		
		print "<td $td \">";
	}
	print "</td>";
}

function LoadDataDb()
{
	global $HOUR_FRACTION, $DAY_OF_WEEK, $DATA_TABLE,$LISTA_ALR_ENABLE_EMAIL;
        global $HOUR_IN_A_DAY,$DATA_FILE,$NUMERI_TELEFONO,$LISTA_ALR_ENABLE_SMS,$LISTA_ALR_ENABLE_FAX;
        $mysql= new Db();
        $mysql->connect();
	
        $HOUR_IN_A_DAY = array();
	for($h=0;$h<24;$h++)
	{
		foreach($HOUR_FRACTION as $i => $val)
		{
			$subkey=sprintf ("%02d:%02d" ,$h,$val);
			array_push($HOUR_IN_A_DAY,$subkey);
			foreach($DAY_OF_WEEK as $i => $day)
			{
                                $key = $day . " " . $subkey;
                                $DATA_TABLE[$key]= array(); 
                                $result=$mysql->execute_select("SELECT nome_sms,numero_sms,id_allarm,text,id FROM rubrica_sms inner join alarm_table on id_allarm = alarm_id && giorno_settimana='$day' && start_ora='$subkey'");
				if(count($result) > 0)
                                {
                                    $tmp=array();
                                    for($row=0;$row<count($result);$row++)
                                    {
                                        $tmp[$row][0]=$result[$row][0]; // nome
                                        $tmp[$row][1]=$result[$row][1]; //numero
                                        $tmp[$row][2]=$result[$row][2]; //-d_allarme
                                        $tmp[$row][3]=$result[$row][3]; //text
                                        $tmp[$row][4]=$result[$row][4]; //id sms table
                                       
                                    }
                                    $DATA_TABLE[$key]= $tmp;
                                }
                                
			}
		}
	} 
        $arr=$mysql->execute_select("SELECT DISTINCT(numero_sms),nome_sms FROM rubrica_sms");
	for($row=0;$row<count($arr);$row++)
            $NUMERI_TELEFONO[$arr[$row][0]]=$arr[$row][1];

        $arr=$mysql->execute_select("SELECT alarm_id,text FROM alarm_table WHERE send_sms = 1;");
	for($row=0;$row<count($arr);$row++)
            $LISTA_ALR_ENABLE_SMS[$arr[$row][0]]=$arr[$row][1];
        
        $arr=$mysql->execute_select("SELECT alarm_id,text FROM alarm_table WHERE send_email = 1;");
	for($row=0;$row<count($arr);$row++)
            $LISTA_ALR_ENABLE_EMAIL[$arr[$row][0]]=$arr[$row][1];
        
        $arr=$mysql->execute_select("SELECT alarm_id,text FROM alarm_table WHERE send_fax = 1;");
	for($row=0;$row<count($arr);$row++)
            $LISTA_ALR_ENABLE_FAX[$arr[$row][0]]=$arr[$row][1];
        

        $mysql->disconnettiDB();
}

function loadDataAllarm()
{
    global $LISTA_ALLARMI;
    $mysql= new Db();
    $mysql->connect();
	
    $arr=$mysql->execute_select("SELECT alarm_id,send_sms,send_fax,send_email,text FROM alarm_table");
    for($row=0;$row<count($arr);$row++)
        $LISTA_ALLARMI[$arr[$row][0]]=array($arr[$row][1],$arr[$row][2],$arr[$row][3],$arr[$row][4]);

    $mysql->disconnettiDB();
}

function loadRubrica()
{
    global $LISTA_RUBRICA_SMS,$LISTA_RUBRICA_FAX,$LISTA_RUBRICA_EMAIL;
    $mysql= new Db();
    $mysql->connect();
	
    $arr=$mysql->execute_select("SELECT id,numero_sms,nome_sms,azienda_sms FROM rubrica_sms group by numero_sms");
    for($row=0;$row<count($arr);$row++)
        $LISTA_RUBRICA_SMS[$arr[$row][1]]=array($arr[$row][2],$arr[$row][3],$arr[$row][0],null);
    
    $arr=$mysql->execute_select("SELECT id,numero_fax,nome_fax,azienda_fax,id_allarm FROM rubrica_fax group by numero_fax");
    for($row=0;$row<count($arr);$row++)
    {
        $tmp=$mysql->execute_select_array("SELECT id_allarm FROM rubrica_fax INNER JOIN alarm_table ON alarm_id = id_allarm && numero_fax =".$arr[$row][1]);
        $LISTA_RUBRICA_FAX[$arr[$row][1]]=array($arr[$row][2],$arr[$row][3],$arr[$row][0],$tmp);
    }
    $arr=$mysql->execute_select("SELECT id,indirizzo_email,nome_email,azienda_email,id_allarm FROM rubrica_email group by indirizzo_email");
    for($row=0;$row<count($arr);$row++)
    {
        $tmp=$mysql->execute_select_array("SELECT id_allarm FROM rubrica_email INNER JOIN alarm_table ON alarm_id = id_allarm && indirizzo_email ='".$arr[$row][1]."'");
    
        $LISTA_RUBRICA_EMAIL[$arr[$row][1]]=array($arr[$row][2],$arr[$row][3],$arr[$row][0],$tmp);
    }
    
    $mysql->disconnettiDB();
}

function StrToDateTime($key)
{
    global $DAY_OF_WEEK_UK;
    
    preg_match("/(...) (..:..)/",$key,$matches);
    list($h, $min) = explode(':',$matches[2]);
    
    $giorno=array_search($matches[1],$DAY_OF_WEEK_UK);
    $today = date("Y-m-d");
    $giorno_now=date('w',strtotime($today));
    //if($giorno_now> $giorno)
    //{
    //    $day=$giorno_now-$giorno;
   // }
   // else
        $day=$giorno-$giorno_now;
    
    $time=time() + 24*$day*3600;
    $data_less_hour=strftime('%Y-%m-%d',$time);
    $data=mktime($h,$min,0,strftime('%m',$time),strftime('%d',$time),strftime('%y',$time));
    
    $data=strftime('%Y-%m-%d %H:%M:%S',$data);
    
    //echo "$giorno $today $giorno_now $day $data_less_hour $data\n";
    //print_r($matches);
    return $data;
}

function incrementaOra($data,$offset)
{
    $data=strtotime( $data );
    $data_sec=$data+ 60*$offset;
    $data_more_hour=strftime('%Y-%m-%d %H:%M:%S',$data_sec);
    return $data_more_hour;
}

function PrintStatoAllarm($num)
{
    global $RISULTATI_PER_PAG;
    $val=0;
    
    $mysql= new Db();
    $mysql->connect();
	
    $start=($RISULTATI_PER_PAG * $num);
    $end=($RISULTATI_PER_PAG * $num)+$RISULTATI_PER_PAG;
    $arr=$mysql->execute_select("SELECT IDCommunication,InsertDate,Destination,Kind,Status,Message FROM communications order by InsertDate desc limit $start,$RISULTATI_PER_PAG ");//  where DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= `InsertDate` order by InsertDate desc");
    #print ("SELECT IDCommunication,InsertDate,Destination,Kind,Status,Message FROM communications order by InsertDate desc limit $start,$RISULTATI_PER_PAG");
    for ($i=0; $i<count($arr);$i++)
    {
        $kind=$arr[$i][4];
        print("<tr>");
        print("<td>".$arr[$i][0]."</td>");
        print "\n<td class=\"middle\">".$arr[$i][1]."</td>\n";
        print "\n<td class=\"middle\">".$arr[$i][2]."</td>\n";
        print "\n<td class=\"middle\">".$arr[$i][3]."</td>\n";
        print "\n<td class=\"middle\"><img src=\"img/table-images/$kind.png\"  alt=\"$kind\" title=\"$kind\"  width=\"20\" height=\"20\" border=\"0\"/>$kind</td>\n";
        print "\n<td class=\"middle\">".substr($arr[$i][5],0,20)."...</td>\n";
        print("\n<td><a href=\"files/php/dettagli_status.php?id=".$arr[$i][0]."\" rel=\"#overlay\" ><img src=\"img/table-images/dettagli.png\"  width=\"20\" height=\"20\" border=\"0\" /></a></td>");
        print("</tr>");
    }
    $mysql->disconnettiDB();
    return true;
}

function PrintForm($ARRAY,$rub)
{
    global $ADMIN;
    $val=0;

    foreach($ARRAY as $i => $v)
    {
        $val++; 
        $key_mod =urlencode("rubrica=$rub&operation=mod&nome=$v[0]&azienda=$v[1]&destinatario=$i&id=$v[2]");
        $key_del =urlencode("rubrica=$rub&operation=del&nome=$v[0]&azienda=$v[1]&destinatario=$i&id=$v[2]");

        print("<tr>");
        print("<td>$val</td>");
        print "\n<td >$v[0]</td>\n";
        print "\n<td >$v[1]</td>\n";
        print "\n<td >$i</td>\n";
        if($ADMIN == $_SESSION['u_name']) 
        {
            print("\n<td ><a href=\"files/php/addnewRubrica.php?key=$key_mod\" rel=\"#overlay\" ><img src=\"img/table-images/mod.png\"  width=\"20\" height=\"20\" border=\"0\" />Modifica</a></td>");
            print("\n<td><a href=\"files/php/addnewRubrica.php?key=$key_del\" rel=\"#overlay\" ><img src=\"img/table-images/delete.png\"  width=\"20\" height=\"20\" border=\"0\" />Elimina</a></td>");
        }
        print("</tr>");
    }

    return true;
}

function checkLogin()
{
    $val=true;
    session_start();
    
    if(! isset($_SESSION['u_name']))
    {   
        $arr=explode("/",($_SERVER['PHP_SELF']));
        $url = "http://" . $_SERVER['SERVER_NAME'] . "/index.php";
        $url.= "?url=".$_SERVER["REQUEST_URI"];
        header( "Location: $url" ) ;
        $val=false;
        
    }
    //if logout then destroy the session and redirect the user
    if(isset($_GET['logout']))
    {
            session_destroy();
            header("http://" . $_SERVER['SERVER_NAME'] . "/");	
    }
    
    return $val;
}

function printHeader($header=true)
{
   
    //<script src="files/js/coda.js" type="text/javascript"></script>
//    <script type="text/javascript">
//        $(document).ready(function() {
//            $("#navbar ul li").click(function() {
//                    $("#navbar ul li").removeClass("selected"); //Remove any "active" class
//                    $(this).addClass("selected"); //Add "active" class to selected tab
//                    $(activeTab).fadeIn(); //Fade in the active ID content
//                    return false;
//             });	
//        });	
//        
//        <script src="files/js/jquery-1.3.min.js" type="text/javascript"></script>
        //<script src="files/js/jquery.tools.min.js" type="text/javascript"> </script>
        
//        </script>
    
//            header(\'Cache-Control: no-store, no-cache, must-revalidate\');
//            header(\'Cache-Control: post-check=0, pre-check=0\', false);
//    
    if(false == checkLogin())
        return false;
    
    session_start();
    
    // if session is not set redirect the user
    
    
    global $ADMIN;
    if(true== $header)
    {
        print('

            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                <html xmlns="http://www.w3.org/1999/xhtml" lang="it">
            <head>

            <link rel="stylesheet" type="text/css" href="style/overlay-apple.css"/> 

            <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
            <!-- STYLE -->
            <link href="./style/topbar.css" rel="stylesheet" type="text/css" />
            <link rel="stylesheet" href="./style/body.css" type="text/css" />


            <!-- page title -->

            <title>Spy Embankments</title>
            </head>


            <body>
                    <div id="sitename" class="clear">
                            <h1> SPY Embankments <a href="./files/php/LogOut.php"><span>Log Out</span></a> </h1> 

                    </div>
                    <div id="navbar">	
                                    <ul class="sf-menu clear"> 
                                            <!-- PAGE NAVIGATION -->

                                            <li >
                                                <a href="Home.php"><span>Home</span></a>
                                            </li>
                                            <li>
                                                <a href="Archivio.php"><span>Archivio</span></a>
                                            </li>
                                            <li >
                                                <a href="Calendario.php"><span>Reperibilit&agrave;</span></a>
                                            </li>
                                            <li>
                                                <a href="Rubrica.php"><span>Rubrica</span></a>
                                            </li>
                                            <li>
                                                <a href="AbilitaAllarmi.php"><span>Configura Allarmi</span></a>
                                            </li>');
            if($ADMIN == $_SESSION['u_name'])
            {

                                            print('<li>
                                                <a href="Impostazioni.php"><span>Impostazioni</span></a>
                                            </li>');
                                            print('<li>
                                                <a href="Immagine.php"><span>Immagine</span></a>
                                            </li>');
            }
             print('                                       


                                    </ul>
                    </div>');
    }
    return true;
}

function sectionIsSelected($sezioni)
{
    for($i=0;$i<15;$i++) //numero di sezioni 
    {
        if($sezioni[$i]==($i+1))
            return 1;
    }
    return 0;
    
}

function selectDatiDb($start_data,$end_data,$sezioni)
{
        $tring_sez=selectSezioni($sezioni);
        //global $MYSQL_SEZIONI;
        
	$msql  = new Db;
	$msql->connect();
	
        if(sectionIsSelected($sezioni))
        {
            $query="SELECT data,$tring_sez FROM dati_impianto where data >= '$start_data' and data <= '$end_data'"; 
            $arr=$msql->execute_select($query);       
        }
        
        if($sezioni[15]==16)
        {
            $s_query = "SELECT data,valore FROM rasponi where data >= '$start_data' and data <= '$end_data';";
            $arr_Rasponi=$msql->execute_select($s_query);
            $arr=mergeArray($arr,$arr_Rasponi);
            
        }
       
	$righe=count($arr);
        
        $colonne=count($arr[0]);
        $html='';
	for ($row = 0; $row < $righe; $row++)
	{
                $html.=("<tr>");
        
		for ($col=0;$col< $colonne ; $col++)
		{
                    $val=$arr[$row][$col];
                    $html.=("<td>$val</td>\n");
		}
                $html.=("</tr>\n");                    
	}

	$msql->disconnettiDB();
	return array("numero_righe"=>$righe,"html"=>$html);
}

function mergeArray($arr1,$arr2)
{
    $righ_arr1=count($arr1);
    $righ_arr2=count($arr2);
    
    $result=array();
    $arra_na=array();
    $ret_arr=array();
    
    for($i=0;$i<(count($arr1[0])-1);$i++)
    {
        $arra_na[]="n/a";
    }
    
    for ($row = 0; $row < $righ_arr1 ; $row++)
    {
        $arra_tmp=$arr1[$row];
        $arra_tmp[]="n/a";
        $result[$arr1[$row][0]]=$arra_tmp;
    }
    
    for ($r = $row; $r < ($row + $righ_arr2) ; $r++)
    {
        $i=$r-$row;
        $data=$arr2[$i][0];
        
        $array=array_merge((array)$data, (array)$arra_na);
        $array=array_merge((array)$array, (array)$arr2[$i][1]);
        $result[$data]=$array;
    }
    krsort($result);
    $i=0;
    foreach(array_keys($result) as $key)
    {
        $ret_arr[$i]=$result[$key];
        $i++;
    }
    
    return $ret_arr;
        
}

function getColonneArchivio()
{
  return $COLONNE_ARCHIVIO;   
}

function getHeaderSez()
{
    global $HeaderSez;
    return $HeaderSez;
}

function selectSezioni($sezioni)
{
    global $TH_Table,$MYSQL_SEZIONI,$HeaderSez;
    global $TITLE;
    $string="";
    $tmp="";
    
    $TH_Table.="<th>Data&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th>\n";
    
    for($i=0;$i < count($sezioni);$i++)
    {
        if($sezioni[$i] == 1)
        {
            $TH_Table.="<th>P1Pz01&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P1Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.="P1Pz01,P1Rx";
            $HeaderSez.="Sez1Pz01,Sez1Segnale";
            $TITLE="1";
            $tmp=",";
        }
        if($sezioni[$i] == 2)
        {
            $TH_Table.="<th>P2Pz02&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P2Pz03&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P2Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.=$tmp."P2Pz02,P2Pz03,P2Rx";
            $HeaderSez.=$tmp."Sez2Pz02,Sez2Pz03,Sez2Segnale";
            $TITLE.="-2";
            $tmp=",";
        }
        if($sezioni[$i] == 3)
        {
            $TH_Table.="<th>P3Pz04&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P3Pz05&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P3Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.=$tmp."P3Pz04,P3Pz05,P3Rx";
            $HeaderSez.=$tmp."Sez3Pz04,Sez3Pz05,Sez3Segnale";

            $tmp=",";
            $TITLE.="-3";
            
        }
        if($sezioni[$i] == 4)
        {
            $TH_Table.="<th>P4Pz06&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P4Pz07&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P4Pz08&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P4Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.=$tmp."P4Pz06,P4Pz07,P4Pz08,P4Rx";
            $HeaderSez.=$tmp."Sez4Pz06,Sez4Pz07,Sez4Pz08,Sez4Segnale";
            $tmp=",";
            $TITLE.="-4";
            
        }
        if($sezioni[$i] == 5)
        {
            $TH_Table.="<th>P5Pz09&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P5Pz10&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P5Rx&nbsp;&nbsp;&nbsp;</th>\n";
           
            $string.=$tmp."P5Pz09,P5Pz10,P5Rx";
            $HeaderSez.=$tmp."Sez5Pz09,Sez5Pz010,Sez5Segnale";

            $tmp=",";
            $TITLE.="-5";
            
        }
        if($sezioni[$i] == 6)
        {
            $TH_Table.="<th>P6Pz11&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P6Pz12&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P6Pz13&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P6Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.=$tmp."P6Pz11,P6Pz12,P6Pz13,P6Rx";
            $HeaderSez.=$tmp."Sez6Pz11,Sez6Pz12,Sez6Pz13,Sez6Segnale";
            $tmp=",";
            $TITLE.="-6";
            
        }
        if($sezioni[$i] == 7)
        {
            $TH_Table.="<th>P7Pz14&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P7Pz15&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P7Pz16&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P7Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.=$tmp."P7Pz14,P7Pz15,P7Pz16,P7Rx";
            $HeaderSez.=$tmp."Sez7Pz14,Sez7Pz15,Sez7Pz16,Sez7Segnale";
            $tmp=",";
            $TITLE.="-7";
            
        }
        if($sezioni[$i] == 8)
        {
            $TH_Table.="<th>P8Pz17&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P8Pz18&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P8Pz19&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P8Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.=$tmp."P8Pz17,P8Pz18,P8Pz19,P8Rx";
            $HeaderSez.=$tmp."Sez8Pz17,Sez8Pz18,Sez8Pz19,Sez8Segnale";
            $tmp=",";
            $TITLE.="-8";
            
        }
        if($sezioni[$i] == 9)
        {
            $TH_Table.="<th>P9Pz20&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P9Pz21&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P9Pz22&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P9Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.=$tmp."P9Pz20,P9Pz21,P9Pz22,P9Rx";
            $HeaderSez.=$tmp."Sez9Pz20,Sez9Pz21,Sez9Pz22,Sez9Segnale";
            $tmp=",";
            $TITLE.="-9";

        }
        if($sezioni[$i] == 10)
        {
            $TH_Table.="<th>P10Pz23&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P10Pz24&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P10Pz25&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P10Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.=$tmp."P10Pz23,P10Pz24,P10Pz25,P10Rx";
            $HeaderSez.=$tmp."Sez10Pz23,Sez10Pz24,Sez10Pz25,Sez10Segnale";
            $tmp=",";
            $TITLE.="10";

        }if($sezioni[$i] == 11)
        {
            $TH_Table.="<th>P11Pz26&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P11Pz27&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P11Pz28&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P11Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.=$tmp."P11Pz26,P11Pz27,P11Pz28,P11Rx";
            $HeaderSez.=$tmp."Sez11Pz26,Sez11Pz27,Sez11Pz28,Sez11Segnale";

            $tmp=",";

            $TITLE.="-11";

        }
        if($sezioni[$i] == 12)
        {
            $TH_Table.="<th>P12Pz29&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P12Pz30&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P12Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            
            $string.=$tmp."P12Pz29,P12Pz30,P12Rx";
            $HeaderSez.=$tmp."Sez12Pz29,Sez12Pz30,Sez12Segnale";

            $tmp=",";       
            $TITLE.="-12";

        }
        if($sezioni[$i] == 13)
        {
            $TH_Table.="<th>P13Pz31&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P13Pz32&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P13Pz33&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P13Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.=$tmp."P13Pz31,P13Pz32,P13Pz33,P13Rx";
            $HeaderSez.=$tmp."Sez13Pz31,Sez13Pz32,Sez13Pz33,Sez13Segnale";

            $TITLE.="-13";

            $tmp=",";
        }
        if($sezioni[$i] == 14)
        {
            $TH_Table.="<th>P14Pz34&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P14Pz35&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P14Pz36&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P14Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.=$tmp."P14Pz34,P14Pz35,P14Pz36,P14Rx";
            $HeaderSez.=$tmp."Sez14Pz34,Sez14Pz35,Sez14Pz36,Sez14Segnale";
                        
            $TITLE.="-14";

            $tmp=",";
        }
        if($sezioni[$i] == 15)
        {
            $TH_Table.="<th>P15Pz37&nbsp;&nbsp;&nbsp;</th>\n";
            $TH_Table.="<th>P15Rx&nbsp;&nbsp;&nbsp;</th>\n";
            
            $string.=$tmp."P15Pz37,P15Rx";
            $HeaderSez.=$tmp."Sez15Pz37,Sez15Segnale";
            
            $TITLE.="-15";

            $tmp=",";
        }
        
        if($sezioni[$i] == 16)
        {
            $TH_Table.="<th>Rasponi</th>\n";
        }
        
    }
    $MYSQL_SEZIONI=$string;
    
    return $string;
    
}

function selectHeaderSezioni()
{
    global $TH_Table;
    return $TH_Table;
//    print($TH_Table);
}

function rrmdir($dir)
{
    if(is_dir($dir))
    {
        $objects=scandir($dir);
        foreach($objects as $object)
        {
            if($object != "." && $object != "..")
            {
                if(filetype($dir."/".$object) == "dir")
                    rrmdir($dir."/".$object);
                else
                    unlink($dir."/".$object);
            }
        }
        reset($objects);
        rmdir($dir);
    }
}

function MakeWriter($start_data,$end_data,$sezioni)
{
    global $TITLE;
    $fw = new ArchivioWriter($start_data,$end_data,$tring_sez,PATH_ARCHIVIO);
    
    if(sectionIsSelected($sezioni))
    {
        $tring_sez=selectSezioni($sezioni);
        $s_query = "SELECT data,$tring_sez FROM dati_impianto where data >= '$start_data' and data <= '$end_data';";

        

        $archivioSez ="Sez".$TITLE."FROM".$start_data."TO".$end_data;
        $archivioSez=str_replace(" ", "-", $archivioSez);
        $header_string=getHeaderSez();
        $archivio_dir=$fw->writeFile($s_query,$archivioSez,$header_string);
    }
        
    if($sezioni[15]==16)
    {
        
        $s_query = "SELECT data,valore FROM rasponi where data >= '$start_data' and data <= '$end_data';";
        $archivioRasp ="SezRasponiFROM".$start_data."TO".$end_data;
        $archivioRasp=str_replace(" ", "-", $archivioRasp);
        $header_string="Segnale";
        $archivio_dirRasp=$fw->writeFile($s_query,$archivioRasp,$header_string);
        
        $fw->Zip($archivio_dir,$archivio_dir,false);

    }

    
     $nomeDir="Archivio".strftime('%Y-%m-%d_%H:%M:%S',time())."/";
     $dir=PATH_ARCHIVIO.$nomeDir;
     $archivio_dir=realpath("$dir_arch/$archivio_dir");
     $archivio_dirRasp=realpath("$dir_arch/$archivio_dirRasp");
     
     mkdir($dir, 0777); //directory creation
     
     //system(`mv $archivio_dir $archivio_dirRasp $dir`);
     rename($archivio_dir,$dir);
     rename($archivio_dirRasp,$dir);
     
     $fw->Zip($dir,$nomeDir);
     $tmp_dir=realpath($dir);
     rrmdir($tmp_dir);
}

function getGraphurl($idParser,$periodo)
{
    switch($idParser)
    {
     case 1://1:// Sezione 1: 'P1Pz01':
        $ret='sing.graph.php?soglia=1&sommita=P1Pz01&piezo=P1Pz&giorni='.$periodo; 
      break;
      case 2://Sezione 2 'P2Pz02':
        $ret='doub.graph.php?soglia=2&sommita=P2Pz02&tuboaperto=P2Pz03&piezo1=P2Pz&piezo2=P3Pz&giorni='.$periodo; 
      break;
      case 3://Sezione 3 'P3Pz04':
        $ret='doub.graph.php?soglia=3&sommita=P3Pz04&tuboaperto=P3Pz05&piezo1=P4Pz&piezo2=P5Pz&giorni='.$periodo; 
        break;
      case 4: //Sezione 4 'P4Pz06':
        $ret='tree.graph.php?soglia=4&sommita=P4Pz06&tuboaperto=P4Pz07&piede=P4Pz08&piezo1=P6Pz&piezo2=P7Pz&piezo3=P8Pz&giorni='.$periodo; 
        break;
      case 5: //Sezione 5 'P5Pz09':
        $ret='doub.graph.php?soglia=5&sommita=P5Pz09&tuboaperto=P5Pz10&piezo1=P9Pz&piezo2=P10Pz&giorni='.$periodo; 
        break;
      case 6: //Sezione 6 'P6Pz11':
        $ret='tree.graph.php?soglia=6&sommita=P6Pz11&tuboaperto=P6Pz12&piede=P6Pz13&piezo1=P11Pz&piezo2=P12Pz&piezo3=P13Pz&giorni='.$periodo; 
      break;
      case 7: //Sezione 7 'P7Pz14':
        $ret='tree.graph.php?soglia=7&sommita=P7Pz14&tuboaperto=P7Pz15&piede=P7Pz16&piezo1=P14Pz&piezo2=P15Pz&piezo3=P16Pz&giorni='.$periodo; 
      break;
      case 8: //Sezione 8 'P8Pz17':
        $ret='tree.graph.php?soglia=8&sommita=P8Pz17&tuboaperto=P8Pz18&piede=P8Pz19&piezo1=P17Pz&piezo2=P18Pz&piezo3=P19Pz&giorni='.$periodo; 
      break;
      case 9: //Sezione 9 'P9Pz20':
        $ret='tree.graph.php?soglia=9&sommita=P9Pz20&tuboaperto=P9Pz21&piede=P9Pz22&piezo1=P20Pz&piezo2=P21Pz&piezo3=P22Pz&giorni='.$periodo; 
      break;
      case 10: //Sezione 10 'P10Pz23':
        $ret='tree.graph.php?soglia=10&sommita=P10Pz23&tuboaperto=P10Pz24&piede=P10Pz25&piezo1=P23Pz&piezo2=P24Pz&piezo3=P25Pz&giorni='.$periodo; 
      break;
      case 11: //Sezione 11 'P11Pz26':
        $ret='tree.graph.php?soglia=11&sommita=P11Pz26&tuboaperto=P11Pz27&piede=P11Pz28&piezo1=P26Pz&piezo2=P27Pz&piezo3=P28Pz&giorni='.$periodo; 
      break;
      case 12: //Sezione 12 'P12Pz29':
        $ret='doub.graph.php?soglia=12&sommita=P12Pz29&tuboaperto=P12Pz30&piezo1=P29Pz&piezo2=P30Pz&giorni='.$periodo; 
      break;
      case 13: //Sezione 13 'P13Pz31':
        $ret='tree.graph.php?soglia=13&sommita=P13Pz31&tuboaperto=P13Pz32&piede=P13Pz33&piezo1=P31Pz&piezo2=P32Pz&piezo3=P33Pz&giorni='.$periodo; 
      break;
      case 14: //Sezione 14 'P14Pz34':
        $ret='tree.graph.php?soglia=14&sommita=P14Pz34&tuboaperto=P14Pz35&piede=P14Pz36&piezo1=P34Pz&piezo2=P35Pz&piezo3=P36Pz&giorni='.$periodo; 
      break;
      case 15: //Sezione 15 'P15Pz37':
        $ret='sing.graph.php?soglia=15&sommita=P15Pz37&piezo=P37Pz&giorni='.$periodo; 
      break;
      case 16: //Rasponi:
        $ret='rasponi.php?&giorni='.$periodo; 
      break;
    }
    return ("./files/php/$ret");
}

function numRowCommunication()
{
    global $RISULTATI_PER_PAG;
    $msql  = new Db;
    $msql->connect();

    $query="SELECT COUNT(*) FROM  communications"; 
    $arr=$msql->execute_select($query); 
    $msql->disconnettiDB();
    return ($arr[0][0]/$RISULTATI_PER_PAG);
}
//LoadDataDb();
//loadRubrica();


?>
